package com.myapp.struts.menu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;

public class JsonToJava extends IReader {

    private ArrayList<FoodItems> foodItemArrayJSON = new ArrayList<FoodItems>();

    public ArrayList<FoodItems> readJSON(String CountryCode) throws IOException {
        URL url = getClass().getResource("dataFiles/InputFiles/FoodItemData.json");
        File jsonFile = new File(url.getPath());
        BufferedReader br = new BufferedReader(new FileReader(jsonFile));
        String jsonTxt = IOUtils.toString(br);
        JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonTxt);
        JSONArray arr = json.getJSONArray("FoodItemData");
        @SuppressWarnings("rawtypes")
        Iterator iter = arr.iterator();
        while (iter.hasNext()) {
            JSONObject object = (JSONObject) iter.next();
            if (object.getString("-country").equals(Constants.US)) {
                FoodItems f = new FoodItems();
                f.setCountry(object.getString("-country"));
                f.setCategory(object.getString("category"));
                f.setId(object.getString("id"));
                f.setDescription(object.getString("description"));
                f.setPrice(object.getString("price"));
                f.setName(object.getString("name"));

                foodItemArrayJSON.add(f);
            }
        }
        return foodItemArrayJSON;
    }

    public ArrayList<FoodItems> getFoodItemArrayJSON() {
        return foodItemArrayJSON;
    }

    public void setFoodItemArrayJSON(ArrayList<FoodItems> foodItemArrayJSON) {
        this.foodItemArrayJSON = foodItemArrayJSON;
    }

    @Override
    public ArrayList<FoodItems> ReadMenu(String CountryCode) {
        try {
            return readJSON(CountryCode);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
